/**
 * 
 */
package com.dangdang.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dangdang.domain.User;
import com.dangdang.util.Constants;

/**
 * 过滤器 <br>
 * 过滤用户是否登录以及是否通过了邮箱的验证
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-2-2
 */

public class AuthorizeFilter implements Filter {

	private String input;

	public String getInput() {
		return input;
	}

	public void setInput(String input) {
		this.input = input;
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		User user = (User) req.getSession().getAttribute(Constants.USER_KEY);

		StringBuffer uri = req.getRequestURL();
		uri.append("?").append(req.getQueryString());

		/**
		 * 如果用户各项条件军符合,则继续向下操作<br>
		 * 否则将其重定向到登录界面,待其登录后转发到刚才的界面
		 */
		if (user != null && user.isVerify()) {
			chain.doFilter(request, response);
		} else {
			resp.sendRedirect(req.getContextPath() + input + "?uri="
					+ URLEncoder.encode(uri.toString(), "utf-8"));
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// 在web.xml文件里配置的
		input = config.getInitParameter("input");
	}
}
